package com.zhijian.wharf.config;

import com.zhijian.BusinessException;
import com.zhijian.entity.CommonResult;
import com.zhijian.response.enums.ResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常返回处理
 *
 * @Author HCG
 * @DateTime 2019年4月14日 下午3:33:53
 * @Version 1.0.1
 */
@SuppressWarnings("rawtypes")
@Slf4j
public class ResponseJsonExceptionHandler extends AbstractHandlerExceptionResolver implements InitializingBean {

    private HttpMessageConverter messageConverter;

    ResponseJsonExceptionHandler(HttpMessageConverter messageConverter) {
        this.messageConverter = messageConverter;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                              Exception ex) {
        CommonResult resp = CommonResult.error();
        log.error("ctrl exception", ex);
        if (ex instanceof BusinessException) {
            // 自定义异常,补充提示信息
            BusinessException exception = (BusinessException) ex;
            resp.setCode(exception.getExCode());
            resp.setMessage(exception.getExMsg());
            resp.setData(exception.getExInfo());
        } else {
            resp.setCode(ResponseCodeEnum.FAILURE.code);
            resp.setMessage("系统错误，请联系管理员");
        }
        try {
            messageConverter.write(resp, MediaType.APPLICATION_JSON_UTF8, new ServletServerHttpResponse(response));
        } catch (HttpMessageNotWritableException | IOException e) {
            log.error(e.getMessage(), e);
        }
        return new ModelAndView();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (messageConverter == null) {
            throw new Exception("messageConverter is null");
        }
    }
}
